﻿using System.Windows;
using System.Windows.Controls;

namespace IntelligentParkingLot.Base;

public class PasswordEx
{
    public static readonly DependencyProperty PasswordProperty =
        DependencyProperty.RegisterAttached(
            "Password",
            typeof(string),
            typeof(PasswordEx),
            new PropertyMetadata(OnPropertyChanged)
        );

    private static bool _isUpdating;

    public static string GetPassword(DependencyObject d)
    {
        return (string)d.GetValue(PasswordProperty);
    }

    public static void SetPassword(DependencyObject d, string value)
    {
        d.SetValue(PasswordProperty, value);
    }

    private static void OnPropertyChanged(
        DependencyObject d,
        DependencyPropertyChangedEventArgs e
    )
    {
        var pb = d as PasswordBox;
        pb.PasswordChanged -= Pb_PasswordChanged;
        if (!_isUpdating)
            pb.Password = e.NewValue.ToString();
        pb.PasswordChanged += Pb_PasswordChanged;
    }

    private static void Pb_PasswordChanged(object sender, RoutedEventArgs e)
    {
        var pb = sender as PasswordBox;
        _isUpdating = true;
        SetPassword(pb, pb.Password);
        _isUpdating = false;
    }
}